package com.sk.sourcecircle.activity.login;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.main.MainActivity;
import com.sk.sourcecircle.adapter.MyPagerAdapter;
import com.sk.sourcecircle.app.MyApplication;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.entity.UserInfo;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/11/22.
 */

@RuntimePermissions
public class LoginActivity extends BaseActivity implements HandleDataCallBack {

    @BindView(R.id.my_table)
    TabLayout myTable;
    @BindView(R.id.my_pager)
    ViewPager myPager;
    List<Fragment> fragments = new ArrayList<>();
    LoginFragment loginFragment;
    RegisterFragment registerFragment;
    private float lat, lng;

    public ViewPager getMyPager() {
        return myPager;
    }

    public void setMyPager(ViewPager myPager) {
        this.myPager = myPager;
    }

    private LoadingDialog loadingDialog;

    private int type;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    private SsoHandler mSsoHandler;
    private AuthInfo mAuthInfo;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            Log.v("AMapLocationListener", JSON.toJSONString(aMapLocation));
            lat = (float) aMapLocation.getLatitude();
            lng = (float) aMapLocation.getLongitude();
            MyApplication.getInstance().setLat(lat);
            MyApplication.getInstance().setLng(lng);
            SPUtils.put(mContext, "lat", lat);
            SPUtils.put(mContext, "lng", lng);
        }
    };

    public double getLat() {
        return lat;
    }

    public void setLat(float lat) {
        this.lat = lat;
    }

    public float getLng() {
        return lng;
    }

    public void setLng(float lng) {
        this.lng = lng;
    }

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
//初始化AMapLocationClientOption对象


    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }


    public AMapLocationClient getmLocationClient() {
        return mLocationClient;
    }

    public void setmLocationClient(AMapLocationClient mLocationClient) {
        this.mLocationClient = mLocationClient;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", 0);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        initFragments();
        LoginActivityPermissionsDispatcher.startLocationWithPermissionCheck(this);
    }

    @NeedsPermission({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS})
    void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        mLocationOption = new AMapLocationClientOption();

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        //获取一次定位结果：
//该方法默认为false。
        mLocationOption.setOnceLocation(true);

//获取最近3s内精度最高的一次定位结果：
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);

        mLocationOption.setNeedAddress(true);

        mLocationOption.setHttpTimeOut(20000);

//关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        mLocationClient.startLocation();

    }

    private void initFragments() {
        loginFragment = new LoginFragment();
        loginFragment.setMyCallBack(this);
        registerFragment = new RegisterFragment();
        fragments.add(loginFragment);
        fragments.add(registerFragment);

        myPager.setOffscreenPageLimit(2);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.login_array), fragments);
        myPager.setAdapter(adapter);
        myTable.setupWithViewPager(myPager);
    }

    // 向用户说明为什么需要这些权限（可选）
    @OnShowRationale({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("源圈需要使用您的位置！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("决绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @OnPermissionDenied({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS})
    void showDeniedForCamera() {
        Toast.makeText(mContext, "拒绝", Toast.LENGTH_SHORT).show();
    }

    // 用户勾选了“不再提醒”时调用（可选）
    @OnNeverAskAgain({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS})
    void showNeverAskForCamera() {
        new AlertDialog.Builder(this)
                .setMessage("您已禁止定位权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v("onActivityResult", String.valueOf(requestCode));
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }


    /**
     * 新浪登录
     */
    private void isSinaLogin() {
        mAuthInfo = new AuthInfo(mContext, Constants.WEIBO_ID, Constants.REDIRECT_URL, Constants.SCOPE);
        mSsoHandler = new SsoHandler(this, mAuthInfo);
        mSsoHandler.authorize(new AuthDialogListener());
    }

    @Override
    public void handlerSuccessData(String result, int tag) {

        UserInfo userInfo2 = JSON.parseObject(result, UserInfo.class);
        SPUtils.put(mContext, "userId", userInfo2.getData().getUser_id());
        SPUtils.put(mContext, "token", userInfo2.getData().getToken());
        SPUtils.put(mContext, "login", result);
        Log.v("login", userInfo2.getData().getToken());
        if (userInfo2.getData().getPhone() != null && userInfo2.getData().getPhone().length() > 0) {
            loginHx(userInfo2.getData().getHx_login(), userInfo2.getData().getHx_pass());
        } else {
            Intent intent = new Intent(mContext, WxInfoActivity.class);
            intent.putExtra("data", userInfo2.getData());
            intent.putExtra("type", type);
            startActivity(intent);
            finish();
        }

    }

    private void loginHx(String account, String password) {
        EMClient.getInstance().login(account, password, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.cancelDialog();
                        Toast.makeText(mContext, "登录成功！", Toast.LENGTH_SHORT).show();
                    }
                });
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
//                Toast.makeText(mContext,"登录聊天服务器成功",Toast.LENGTH_SHORT).show();
                Log.d("loginHx", "登录聊天服务器成功！");
                if (type == 1) {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                    finish();

                } else {
                    setResult(Activity.RESULT_OK);
                    finish();
                }

            }

            @Override
            public void onProgress(int progress, String status) {


            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.cancelDialog();
                    }
                });
//                Toast.makeText(mContext,"登录聊天服务器失败"+message,Toast.LENGTH_SHORT).show();
                Log.d("loginHx", "登录聊天服务器失败！");
                Log.d("loginHx", message);
                if (type == 1) {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                    finish();

                } else {
                    setResult(Activity.RESULT_OK);
                    finish();
                }
            }
        });
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    /**
     * 新浪回调
     *
     * @author Administrator
     */
    private class AuthDialogListener implements WeiboAuthListener {


        @Override
        public void onComplete(final Bundle bundle) {
            Log.v("SinaRequestListener", bundle.toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String access_token = bundle.getString("access_token");
                    loadingDialog.show();
                    AppApi.weiboLogin(access_token, MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), LoginActivity.this, 10, LoginActivity.this);
                }
            });

        }

        @Override
        public void onWeiboException(WeiboException e) {

        }

        @Override
        public void onCancel() {

        }
    }

    /**
     * 新浪请求接口
     *
     * @author Administrator
     */
    private class SinaRequestListener implements RequestListener {

        @Override
        public void onComplete(String s) {
            Log.v("SinaRequestListener", s);
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Log.v("SinaRequestListener", e.getMessage());
        }
    }

    @Override
    public void sure() {
        super.sure();
        isSinaLogin();
    }
}
